<?php

namespace App\Models;

use App\Models\Traits\UserLikeCategoryHelper;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use DB;

class User extends Authenticatable
{
    use Notifiable;
    use UserLikeCategoryHelper;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'wechat_openid',
        'wechat_avatar',
        'wechat_nickname',
        'telephone',
        'is_vip',
        'vip_start_time',
        'vip_end_time',
        'share_user_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function addresses()
    {
        return $this->hasMany(UserAddress::class);
    }

    public function comments()
    {
        return $this->hasMany(BookComment::class);
    }

    public function user_vip_time_records()
    {
        return $this->hasMany(UserVipTimeRecord::class);
    }

    public static function getSelectOptions()
    {
        $options = DB::table('users')->where('user_type',0)->get(['id', DB::raw('wechat_nickname as text')]);

        $selectOption = [];
        foreach ($options as $option){
            $selectOption[$option->id] = $option->text;
        }
        return $selectOption;
    }

    public function book_list_collects()
    {
        return $this->belongsToMany(BookList::class,'book_list_user_collect_relations','user_id');
    }

    public function carts()
    {
        return $this->hasMany(UserCart::class);
    }

    public function share_users()
    {
        return $this->hasMany(User::class,'share_user_id');
    }

    //获取剩余会员天数
    public function getVipDaysAttribute()
    {
        if($this->is_vip == 1)
        {
            if(!empty($this->vip_end_time) && !empty($this->vip_start_time))
            {
                $timediff = $this->vip_end_time - $this->vip_start_time;
                $day = ceil($timediff/86400);
                return $day;
            }
        }
        return 0;
    }
}
